import Vue from 'vue'
import store from '@/store'
import Router from 'vue-router'
import Home from '@/views/index.vue'
import Login from  '@/views/login.vue'
import Message from  '@/views/message.vue'
import New from  '@/views/new.vue'
import {getUser,getToken} from '@/utils'

Vue.use(Router)

var router= new Router({
  routes: [
    {
      path: '/',
      name: 'home',
      component: Home
    },
    {
      path: '/login',
      name: 'login',
      component: Login
    },
    {
      path: '/message',
      name: 'message',
      component: Message
    },
    {
      path: '/new',
      name: 'new',
      component: New
    }
  ]
})

router.beforeEach((to, from, next) => {
  /**
   * 如果localStorage中的token存在：
   *    1、如果是退出登陆,清理信息，退出
   *    2、如果不是退出登陆，判断store中的用户信息是否存在，如果不存在进行设置
   *
   * 如果localStorage中的token不存在：
   *    1、返回登录界面进行重新登录
   *
   */

  if (to.path === '/login') {
    if(getToken()){
      next({
        path: '/'
      })
    }else{
      next()
    }
    return
  }
  if (getToken()) {
    if (to.path != '/') {
      if(!store.getters.token){
        store.dispatch('setUserInfo');
      }
      next()
    }else{
      next()
    }
  }else {
    if(to.path != '/'){
      next({
        path: '/login'
      })
    }else{
      next()
    }
  }
  /*
  console.info("===1===")
  if(getUser()){
    console.info("===2===")
    if(to.path === "/login"){
      console.info("===3===")
      next();
    }else{
      console.info("===4===")
      if(!store.getters.token){
        console.info("===5===")
        store.dispatch('setUserInfo');
      }
    }
    console.info("===6===")
  }else{
    console.info("===7===")
    next('/login')
    return;
  }
  console.info("===8===")
 next();*/
});



export default router;
